package com.ids.enigha;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.ids.enigha.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterPage extends Activity {

	EditText imei_et, username_et, password_et, deviceid_et, devicename_et,
			confirmpwd_et;
	Button register_in_btn;
	String username = null;
	String password = null;
	String deviceid = null;
	String devicename = null;
	String identifier = null;
	String confirmpwd = null;
	SharedPreferences loginpreferences;

	String deviceName = null;
	String deviceMan = null;
	
	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.register_page);
		
		imei_et = (EditText) findViewById(R.id.imeinumber_reg);

		
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		
		identifier = tm.getDeviceId();
		
		
		deviceName = android.os.Build.MODEL;
		
		deviceMan = android.os.Build.MANUFACTURER;
		deviceName = deviceName+" "+deviceMan;
		
		System.out.println("raj deviceName: "+deviceName);

		imei_et.setText(identifier);
		imei_et.setClickable(false);
		imei_et.setEnabled(false);

		username_et = (EditText) findViewById(R.id.username_reg);
		password_et = (EditText) findViewById(R.id.password_reg);
		deviceid_et = (EditText) findViewById(R.id.deviceid_reg);
		devicename_et = (EditText) findViewById(R.id.devicename_reg);
		confirmpwd_et = (EditText) findViewById(R.id.cpassword_reg);

		register_in_btn = (Button) findViewById(R.id.register_in_btn);

		register_in_btn.setOnClickListener(new OnClickListener() {

			@SuppressLint("ShowToast")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!isGPSEnabled())
				{
					try
					{
						Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
						intent.putExtra("enabled", true);
						sendBroadcast(intent);
						turnGPSOn();
					}
					catch(Exception ex)
					{
						System.out.println("raj exception in turning GPS on: "+ex);
						showSettingsAlert();
					}
					return;
				}
				username = username_et.getText().toString();
				password = password_et.getText().toString();
				deviceid = deviceid_et.getText().toString();
				devicename = devicename_et.getText().toString();
				confirmpwd = confirmpwd_et.getText().toString();
				
				if(username == null || username.trim().length() < 1)
					Toast.makeText(getApplicationContext(), "Please Enter User ID", Toast.LENGTH_LONG).show();
				else if(password == null || password.trim().length() < 1)
					Toast.makeText(getApplicationContext(), "Please Enter Password", Toast.LENGTH_LONG).show();
				else if(confirmpwd == null || confirmpwd.trim().length() < 1)
					Toast.makeText(getApplicationContext(), "Please Enter Confirm Password", Toast.LENGTH_LONG).show();
				else if(!password.equals(confirmpwd))
					Toast.makeText(getApplicationContext(), "Password doesn't Match", Toast.LENGTH_LONG).show();
				else
				{
					if(isOnline())
					{
						new DownloadData().execute();
					}
					else
					{
						Toast.makeText(
								getApplicationContext(),
								"Internet is Not Available",
								Toast.LENGTH_LONG);
					}
				}
			}
		});
	}

	public int parsing_status() {
		int status = 0;
		String paramFormatStr = "{devicename:\"%s\",deviceid:\"%s\",userid:\"%s\",passwd:\"%s\"}";

		if(deviceName == null)
			deviceName = username;
		
		String param = String.format(paramFormatStr, deviceName, identifier,
				username, password);
		Log.d("parsing string", "parsing =" + param);
		String path = "http://192.237.167.247:9090/eNigha-trackingserver-1.0-SNAPSHOT/devices/";
		try {
			int statuscode = makeRequest(path, param);
			status = statuscode;
			Log.d("TAG", "------> codestatus" + statuscode);
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("TAG", "------catch");
		}

		return status;

	}

	public static int makeRequest(String path, String param/* Map params */) {

		DefaultHttpClient httpclient = null;
		HttpPost httpost = null;
		HttpResponse response = null;

		try {
			httpclient = new DefaultHttpClient();
			httpost = new HttpPost(path);
			System.out.println("this url is " + path);
			JSONObject holder = new JSONObject();
			JSONObject data = new JSONObject(param);
			holder.put("Device", data);
			httpost.setHeader("Device", param);
			httpost.setHeader("Content-type", "application/json");
			Log.d("httppost", "" + httpost);
			response = httpclient.execute(httpost);
			Log.d("response", "" + response.getStatusLine().getStatusCode());
			Log.d("response", "" + response);

		} catch (Exception e) {

			return 0;
		} finally {

			if (httpclient == null) {

			} else {
				try {
					response.getEntity().getContent().close();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return response.getStatusLine().getStatusCode();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();

	}

	ProgressDialog pDialog;

	class DownloadData extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(RegisterPage.this);
			pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pDialog.setMessage("Please wait....");
			pDialog.show();
		}

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			int StatusCode = 0;
			StatusCode = parsing_status();
			Log.d("asynctask", "else 1 asyn status code=" + StatusCode);
			return StatusCode;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (pDialog != null && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			if (result == 200) {

				SharedPreferences.Editor editor = getSharedPreferences(
						"ENIGHA_DETAILS", MODE_PRIVATE).edit();

				editor.putString("USERNAME", username);
				editor.putString("PASSWORD", password);
				editor.putString("DEVICE_ID", identifier);
				editor.putString("DEVICE_NAME", devicename);
				editor.commit();

				Toast.makeText(getApplicationContext(), "Successfully Registered", Toast.LENGTH_LONG)
						.show();

//				Intent login_intent = new Intent(getApplicationContext(),
//						DisplayMapView.class);
//				login_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//						| Intent.FLAG_ACTIVITY_NEW_TASK);
//				startActivity(login_intent);
				
				Intent service = new Intent(getApplicationContext(), TrackingService.class);
				startService(service);
				saveIsTrackingStarted(true);
				displayTrackStartedDialog();
				//startActivity(new Intent(getApplicationContext(), DisplayMapView.class));
			} else {
				Toast.makeText(getApplicationContext(), "Registration Failed", Toast.LENGTH_LONG)
						.show();
			}
		}

	}
	
	private Boolean isOnline() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
        }
        return false;
	}
	public void saveIsTrackingStarted(boolean isTrackingStarted)
	{
		SharedPreferences prefs = getSharedPreferences("ENIGHA_DETAILS", MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putBoolean("isTrackingStarted", isTrackingStarted);
		editor.commit();
	}
	public boolean isGPSEnabled()
    {
    	LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);;
        boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return enabled;
    }
	public void turnGPSOn() {

		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (!provider.contains("gps")) {
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}

	private void turnGPSOff() {
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (provider.contains("gps")) { 
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}
	public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
      
        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");	  	        
        alertDialog.setMessage("GPS is not enabled! eNigha Application needs GPS for tracking the location.\n" +
        		"Do you want to enable?");	  
        
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
  
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // Showing Alert Message
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
	public void displayTrackStartedDialog(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
      
        // Setting Dialog Title
        alertDialog.setTitle("eNiGHA");	  	        
        alertDialog.setMessage(" Registration Succuessful!.\nTracking started. Do you want to EXIT the application.");	  
        
        alertDialog.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            	finish();
            }
        });
  
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            onBackPressed();
            finish();
            }
        });
  
        // Showing Alert Message
        alertDialog.setCancelable(false);
        alertDialog.show();
    }


}
